import React, { useState, useEffect, useRef } from 'react';
import styles from './index.module.css';

const Cure = () => {
    // 状态管理
    const [activeTab, setActiveTab] = useState('services');
    const [searchTerm, setSearchTerm] = useState('');
    const [orders, setOrders] = useState([]);
    const [appointments, setAppointments] = useState([]);
    const [tempOrder, setTempOrder] = useState(null);
    const [tempAppointment, setTempAppointment] = useState(null);
    const [selectedOrderId, setSelectedOrderId] = useState(null);
    const [selectedAppointmentId, setSelectedAppointmentId] = useState(null);
    const [selectedClient, setSelectedClient] = useState(null);
    const [currentProjectId, setCurrentProjectId] = useState(null);
    const [specModalOpen, setSpecModalOpen] = useState(false);
    const [clientPhone, setClientPhone] = useState('');
    const [notes, setNotes] = useState('');
    const [selectedStaff, setSelectedStaff] = useState('');
    const [selectedRoom, setSelectedRoom] = useState('');
    const [selectedPaymentMethod, setSelectedPaymentMethod] = useState('cash');
    const [selectedItems, setSelectedItems] = useState([]);

    // 项目数据映射
    const projectMap = {
        tuina: {
            name: "推拿按摩",
            specs: [
                { duration: "30分钟", price: 98, id: "tuina-30" },
                { duration: "60分钟", price: 168, id: "tuina-60" }
            ]
        },
        zhenjiu: {
            name: "针灸治疗",
            specs: [
                { duration: "30分钟", price: 128, id: "zhenjiu-30" },
                { duration: "60分钟", price: 198, id: "zhenjiu-60" }
            ]
        },
        aijiu: {
            name: "艾灸调理",
            specs: [
                { duration: "30分钟", price: 88, id: "aijiu-30" },
                { duration: "60分钟", price: 158, id: "aijiu-60" },
                { duration: "90分钟", price: 228, id: "aijiu-90" }
            ]
        },
        baguan: {
            name: "拔罐疗法",
            specs: [
                { duration: "20分钟", price: 68, id: "baguan-20" },
                { duration: "45分钟", price: 98, id: "baguan-45" }
            ]
        },
        zudi: {
            name: "足底按摩",
            specs: [
                { duration: "45分钟", price: 88, id: "zudi-45" },
                { duration: "60分钟", price: 128, id: "zudi-60" }
            ]
        },
        jingyou: {
            name: "精油SPA",
            specs: [
                { duration: "60分钟", price: 198, id: "jingyou-60" },
                { duration: "90分钟", price: 298, id: "jingyou-90" }
            ]
        },
        guasha: {
            name: "刮痧排毒",
            specs: [
                { duration: "30分钟", price: 78, id: "guasha-30" },
                { duration: "45分钟", price: 108, id: "guasha-45" }
            ]
        },
        jianjing: {
            name: "肩颈理疗",
            specs: [
                { duration: "45分钟", price: 118, id: "jianjing-45" },
                { duration: "60分钟", price: 158, id: "jianjing-60" }
            ]
        },
        beibu: {
            name: "背部护理",
            specs: [
                { duration: "60分钟", price: 168, id: "beibu-60" },
                { duration: "90分钟", price: 238, id: "beibu-90" }
            ]
        }
    };

    // 客户数据
    const clientsData = [
        {
            id: 1,
            name: "张三",
            phone: "13800138000",
            gender: "男",
            age: 35,
            address: "北京市朝阳区",
            history: [
                { date: "2023-05-15", project: "推拿按摩(60分钟)" },
                { date: "2023-05-22", project: "艾灸调理(30分钟)" }
            ]
        },
        {
            id: 2,
            name: "李四",
            phone: "13900139000",
            gender: "女",
            age: 28,
            address: "上海市静安区",
            history: [
                { date: "2023-06-01", project: "针灸治疗(30分钟)" }
            ]
        },
        {
            id: 3,
            name: "王五",
            phone: "13700137000",
            gender: "男",
            age: 42,
            address: "广州市天河区",
            history: [
                { date: "2023-05-10", project: "拔罐疗法(45分钟)" },
                { date: "2023-05-17", project: "推拿按摩(30分钟)" }
            ]
        },
        {
            id: 4,
            name: "赵六",
            phone: "13600136000",
            gender: "女",
            age: 31,
            address: "深圳市福田区",
            history: []
        },
        {
            id: 5,
            name: "钱七",
            phone: "13500135000",
            gender: "男",
            age: 55,
            address: "杭州市西湖区",
            history: [
                { date: "2023-05-05", project: "肩颈理疗(60分钟)" }
            ]
        }
    ];

    // 初始化数据
    useEffect(() => {
        // 初始化订单
        const initOrders = [
            {
                id: 1001,
                clientId: 1,
                clientName: "张三",
                clientPhone: "13800138000",
                items: [
                    { id: "tuina", name: "推拿按摩", specId: "tuina-60", duration: "60分钟", price: 168 }
                ],
                totalAmount: 168,
                status: "待支付",
                createTime: "2023-06-15 10:30"
            },
            {
                id: 1002,
                clientId: 2,
                clientName: "李四",
                clientPhone: "13900139000",
                items: [
                    { id: "aijiu", name: "艾灸调理", specId: "aijiu-90", duration: "90分钟", price: 228 },
                    { id: "guasha", name: "刮痧排毒", specId: "guasha-30", duration: "30分钟", price: 78 }
                ],
                totalAmount: 306,
                status: "待支付",
                createTime: "2023-06-15 14:15"
            },
            {
                id: 1003,
                clientId: 3,
                clientName: "王五",
                clientPhone: "13700137000",
                items: [
                    { id: "jianjing", name: "肩颈理疗", specId: "jianjing-60", duration: "60分钟", price: 158 }
                ],
                totalAmount: 158,
                status: "待支付",
                createTime: "2023-06-14 09:45"
            },
            {
                id: 1004,
                clientId: 5,
                clientName: "钱七",
                clientPhone: "13500135000",
                items: [
                    { id: "jingyou", name: "精油SPA", specId: "jingyou-90", duration: "90分钟", price: 298 },
                    { id: "baguan", name: "拔罐疗法", specId: "baguan-45", duration: "45分钟", price: 98 }
                ],
                totalAmount: 396,
                status: "待支付",
                createTime: "2023-06-14 16:20"
            }
        ];

        // 初始化预约
        const initAppointments = [
            {
                id: 2001,
                clientId: 1,
                clientName: "张三",
                clientPhone: "13800138000",
                items: [
                    { id: "tuina", name: "推拿按摩", specId: "tuina-60", duration: "60分钟", price: 168 }
                ],
                totalAmount: 168,
                appointmentTime: "2023-06-16 15:00",
                status: "已预约",
            },
            {
                id: 2002,
                clientId: 4,
                clientName: "赵六",
                clientPhone: "13600136000",
                items: [
                    { id: "aijiu", name: "艾灸调理", specId: "aijiu-60", duration: "60分钟", price: 158 }
                ],
                totalAmount: 158,
                appointmentTime: "2023-06-16 10:30",
                status: "已预约",
            },
            {
                id: 2003,
                clientId: 3,
                clientName: "王五",
                clientPhone: "13700137000",
                items: [
                    { id: "zhenjiu", name: "针灸治疗", specId: "zhenjiu-30", duration: "30分钟", price: 128 },
                    { id: "baguan", name: "拔罐疗法", specId: "baguan-45", duration: "45分钟", price: 98 }
                ],
                totalAmount: 226,
                appointmentTime: "2023-06-17 09:00",
                status: "已预约",
            }
        ];

        setOrders(initOrders);
        setAppointments(initAppointments);
    }, []);

    // 当客户电话改变时查找客户信息
    useEffect(() => {
        if (clientPhone) {
            const foundClient = clientsData.find(client => client.phone === clientPhone);
            setSelectedClient(foundClient || null);
        } else {
            setSelectedClient(null);
        }
    }, [clientPhone]);

    // 计算金额
    const calculateAmounts = () => {
        let subtotal = 0;
        const discount = 0;

        if (tempOrder) {
            subtotal = tempOrder.totalAmount;
        } else if (tempAppointment) {
            subtotal = tempAppointment.totalAmount;
        } else {
            subtotal = selectedItems.reduce((sum, item) => sum + item.price, 0);
        }

        const total = subtotal - discount;
        return { subtotal, discount, total };
    };

    // 切换Tab
    const handleTabChange = (tab) => {
        setActiveTab(tab);
        setSearchTerm('');
    };

    // 搜索处理
    const handleSearch = (e) => {
        setSearchTerm(e.target.value.toLowerCase().trim());
    };

    // 过滤服务项目
    const filteredServices = () => {
        if (!searchTerm) return Object.keys(projectMap);
        
        return Object.keys(projectMap).filter(projectId => 
            projectMap[projectId].name.toLowerCase().includes(searchTerm)
        );
    };

    // 过滤订单
    const filteredOrders = () => {
        const pendingOrders = orders.filter(o => o.status === "待支付");
        if (!searchTerm) return pendingOrders;
        
        return pendingOrders.filter(order =>
            order.clientName.toLowerCase().includes(searchTerm) ||
            order.clientPhone.includes(searchTerm) ||
            order.id.toString().includes(searchTerm) ||
            order.items.some(item => item.name.toLowerCase().includes(searchTerm))
        );
    };

    // 过滤预约
    const filteredAppointments = () => {
        if (!searchTerm) return appointments;
        
        return appointments.filter(appointment =>
            appointment.clientName.toLowerCase().includes(searchTerm) ||
            appointment.clientPhone.includes(searchTerm) ||
            appointment.id.toString().includes(searchTerm) ||
            appointment.appointmentTime.includes(searchTerm) ||
            appointment.items.some(item => item.name.toLowerCase().includes(searchTerm))
        );
    };

    // 打开规格选择弹窗
    const openSpecModal = (projectId) => {
        setCurrentProjectId(projectId);
        setSpecModalOpen(true);
    };

    // 关闭规格选择弹窗
    const closeSpecModal = () => {
        setSpecModalOpen(false);
        setCurrentProjectId(null);
    };

    // 选择规格
    const selectSpec = (spec) => {
        if (!currentProjectId) return;
        
        const project = projectMap[currentProjectId];
        const newItem = {
            id: currentProjectId,
            name: project.name,
            specId: spec.id,
            duration: spec.duration,
            price: spec.price
        };

        // 检查是否已存在该项目
        const existingIndex = selectedItems.findIndex(item => item.specId === spec.id);
        if (existingIndex >= 0) {
            // 移除已存在的项目（取消选择）
            const updatedItems = [...selectedItems];
            updatedItems.splice(existingIndex, 1);
            setSelectedItems(updatedItems);
        } else {
            // 添加新项目
            setSelectedItems([...selectedItems, newItem]);
        }

        // 更新临时订单或预约
        if (tempOrder) {
            const updatedOrder = { ...tempOrder };
            const itemIndex = updatedOrder.items.findIndex(i => i.specId === spec.id);
            
            if (itemIndex >= 0) {
                updatedOrder.items.splice(itemIndex, 1);
            } else {
                updatedOrder.items.push(newItem);
            }
            
            updatedOrder.totalAmount = updatedOrder.items.reduce((sum, item) => sum + item.price, 0);
            setTempOrder(updatedOrder);
        } else if (tempAppointment) {
            const updatedAppointment = { ...tempAppointment };
            const itemIndex = updatedAppointment.items.findIndex(i => i.specId === spec.id);
            
            if (itemIndex >= 0) {
                updatedAppointment.items.splice(itemIndex, 1);
            } else {
                updatedAppointment.items.push(newItem);
            }
            
            updatedAppointment.totalAmount = updatedAppointment.items.reduce((sum, item) => sum + item.price, 0);
            setTempAppointment(updatedAppointment);
        }

        closeSpecModal();
    };

    // 移除已选项目
    const removeSelectedItem = (specId) => {
        const updatedItems = selectedItems.filter(item => item.specId !== specId);
        setSelectedItems(updatedItems);

        // 更新临时订单或预约
        if (tempOrder) {
            const updatedOrder = { ...tempOrder };
            updatedOrder.items = updatedOrder.items.filter(i => i.specId !== specId);
            updatedOrder.totalAmount = updatedOrder.items.reduce((sum, item) => sum + item.price, 0);
            setTempOrder(updatedOrder);
        } else if (tempAppointment) {
            const updatedAppointment = { ...tempAppointment };
            updatedAppointment.items = updatedAppointment.items.filter(i => i.specId !== specId);
            updatedAppointment.totalAmount = updatedAppointment.items.reduce((sum, item) => sum + item.price, 0);
            setTempAppointment(updatedAppointment);
        }
    };

    // 加载订单详情 - 支持取消选中
    const loadOrderDetails = (orderId, e) => {
        // 如果点击的是已选中的订单，则取消选中
        if (selectedOrderId === orderId) {
            resetSelection();
            return;
        }

        const order = orders.find(o => o.id === orderId);
        if (!order) return;

        setSelectedOrderId(orderId);
        setSelectedAppointmentId(null);
        setTempAppointment(null);
        setTempOrder(JSON.parse(JSON.stringify(order)));
        setClientPhone(order.clientPhone);
        setSelectedItems([...order.items]);
        setNotes(order.notes || '');
        setSelectedStaff(order.staffId || '');
        setSelectedRoom(order.roomId || '');
    };

    // 加载预约详情 - 支持取消选中
    const loadAppointmentDetails = (appointmentId) => {
        // 如果点击的是已选中的预约，则取消选中
        if (selectedAppointmentId === appointmentId) {
            resetSelection();
            return;
        }

        const appointment = appointments.find(a => a.id === appointmentId);
        if (!appointment) return;

        setSelectedAppointmentId(appointmentId);
        setSelectedOrderId(null);
        setTempOrder(null);
        setTempAppointment(JSON.parse(JSON.stringify(appointment)));
        setClientPhone(appointment.clientPhone);
        setSelectedItems([...appointment.items]);
        setNotes(appointment.notes || '');
        setSelectedStaff(appointment.staffId || '');
        setSelectedRoom(appointment.roomId || '');
    };

    // 重置选择状态（取消选中）
    const resetSelection = () => {
        setSelectedOrderId(null);
        setSelectedAppointmentId(null);
        setTempOrder(null);
        setTempAppointment(null);
        setSelectedItems([]);
        setNotes('');
    };

    // 重置表单
    const resetForm = () => {
        setClientPhone('');
        setNotes('');
        setSelectedStaff('');
        setSelectedRoom('');
        setSelectedPaymentMethod('cash');
        setSelectedClient(null);
        setSelectedItems([]);
        setSelectedOrderId(null);
        setSelectedAppointmentId(null);
        setTempOrder(null);
        setTempAppointment(null);
    };

    // 确认订单修改
    const confirmOrderChanges = () => {
        if (!selectedOrderId || !tempOrder) return;

        if (tempOrder.items.length === 0) {
            alert('订单至少需要包含一个服务项目');
            return;
        }

        const updatedOrders = [...orders];
        const orderIndex = updatedOrders.findIndex(o => o.id === selectedOrderId);
        
        if (orderIndex !== -1) {
            updatedOrders[orderIndex] = {
                ...updatedOrders[orderIndex],
                items: tempOrder.items,
                totalAmount: tempOrder.totalAmount,
                notes: notes
            };
            
            setOrders(updatedOrders);
            alert(`订单修改成功！\n订单号: ${updatedOrders[orderIndex].id}\n新总金额: ¥${updatedOrders[orderIndex].totalAmount.toFixed(2)}`);
        }
    };

    // 完成支付
    const completePayment = () => {
        if (!selectedOrderId || !tempOrder) return;

        const updatedOrders = [...orders];
        const orderIndex = updatedOrders.findIndex(o => o.id === selectedOrderId);
        
        if (orderIndex === -1) return;

        updatedOrders[orderIndex] = {
            ...tempOrder,
            status: "已支付",
            paymentMethod: selectedPaymentMethod,
            paymentTime: new Date().toLocaleString('zh-CN'),
            notes: notes
        };

        setOrders(updatedOrders);
        resetSelection();
        
        let paymentMethodText = '';
        switch (selectedPaymentMethod) {
            case 'cash': paymentMethodText = '现金支付'; break;
            case 'wechat': paymentMethodText = '微信支付'; break;
            case 'alipay': paymentMethodText = '支付宝'; break;
            case 'card': paymentMethodText = '银行卡支付'; break;
        }

        alert(`支付成功！\n订单号: ${updatedOrders[orderIndex].id}\n支付方式: ${paymentMethodText}\n总金额: ¥${updatedOrders[orderIndex].totalAmount.toFixed(2)}`);
    };

    // 确认预约安排
    const confirmAppointment = () => {
        if (!selectedAppointmentId || !tempAppointment) return;

        if (tempAppointment.items.length === 0) {
            alert('预约至少需要包含一个服务项目');
            return;
        }

        if (!selectedStaff) {
            alert('请选择理疗师');
            return;
        }

        if (!selectedRoom) {
            alert('请选择理疗房间');
            return;
        }

        const staffName = document.querySelector(`option[value="${selectedStaff}"]`)?.text || '';
        const roomName = document.querySelector(`option[value="${selectedRoom}"]`)?.text || '';

        const updatedAppointments = [...appointments];
        const appointmentIndex = updatedAppointments.findIndex(a => a.id === selectedAppointmentId);
        
        if (appointmentIndex !== -1) {
            updatedAppointments[appointmentIndex] = {
                ...tempAppointment,
                staffId: selectedStaff,
                staffName: staffName,
                roomId: selectedRoom,
                roomName: roomName,
                notes: notes
            };
            
            setAppointments(updatedAppointments);
            alert(`预约安排成功！\n预约号: ${updatedAppointments[appointmentIndex].id}\n客户: ${updatedAppointments[appointmentIndex].clientName}\n时间: ${updatedAppointments[appointmentIndex].appointmentTime}\n理疗师: ${staffName}\n房间: ${roomName}`);
        }

        resetSelection();
    };

    // 创建新订单
    const createNewOrder = () => {
        if (!clientPhone) {
            alert('请输入客户电话号码');
            return;
        }

        if (selectedItems.length === 0) {
            alert('请至少选择一个项目及规格');
            return;
        }

        if (!selectedStaff) {
            alert('请选择理疗师');
            return;
        }

        if (!selectedRoom) {
            alert('请选择理疗房间');
            return;
        }

        const staffName = document.querySelector(`option[value="${selectedStaff}"]`)?.text || '';
        const roomName = document.querySelector(`option[value="${selectedRoom}"]`)?.text || '';

        const totalAmount = selectedItems.reduce((sum, item) => sum + item.price, 0);
        const newOrder = {
            id: Math.floor(Date.now() / 1000),
            clientId: selectedClient ? selectedClient.id : null,
            clientName: selectedClient ? selectedClient.name : '新客户',
            clientPhone: clientPhone,
            items: selectedItems,
            totalAmount: totalAmount,
            status: "待支付",
            notes: notes,
            createTime: new Date().toLocaleString('zh-CN'),
            staffId: selectedStaff,
            staffName: staffName,
            roomId: selectedRoom,
            roomName: roomName
        };

        setOrders([newOrder, ...orders]);
        setActiveTab('orders');
        alert(`订单创建成功！\n订单号: ${newOrder.id}\n理疗师: ${staffName}\n房间: ${roomName}\n总金额: ¥${newOrder.totalAmount.toFixed(2)}`);
        resetForm();
    };

    // 处理操作按钮点击
    const handleActionButtonClick = () => {
        if (selectedOrderId) {
            completePayment();
        } else if (selectedAppointmentId) {
            confirmAppointment();
        } else {
            createNewOrder();
        }
    };

    // 计算金额
    const { subtotal, discount, total } = calculateAmounts();

    return (
        <div className={styles.fullscreenContainer}>
            <main className={styles.fullscreenContent}>
                <div className={styles.flexContainer}>
                    {/* 左侧：服务、订单和预约Tab */}
                    <div className={styles.leftColumn}>
                        <div className={styles.cardStyle}>
                            {/* Tab 切换 */}
                            <div className={styles.tabsContainer}>
                                <div className={styles.tabs}>
                                    <div 
                                        className={`${styles.tab} ${activeTab === 'services' ? styles.active : ''}`}
                                        onClick={() => handleTabChange('services')}
                                    >
                                        服务项目
                                    </div>
                                    <div 
                                        className={`${styles.tab} ${activeTab === 'appointments' ? styles.active : ''}`}
                                        onClick={() => handleTabChange('appointments')}
                                    >
                                        预约安排
                                    </div>
                                    <div 
                                        className={`${styles.tab} ${activeTab === 'orders' ? styles.active : ''}`}
                                        onClick={() => handleTabChange('orders')}
                                    >
                                        订单记录
                                    </div>
                                </div>
                            </div>

                            {/* 搜索框 */}
                            <div className={styles.searchContainer}>
                                <i className={`fa fa-search ${styles.searchIcon}`}></i>
                                <input 
                                    type="text" 
                                    className={styles.searchInput} 
                                    placeholder="搜索服务项目、订单或预约..."
                                    value={searchTerm}
                                    onChange={handleSearch}
                                />
                            </div>

                            {/* 服务项目内容 */}
                            {activeTab === 'services' && (
                                <div className={styles.tabContentActive}>
                                    <div className={styles.projectContainer}>
                                        {filteredServices().map(projectId => {
                                            const project = projectMap[projectId];
                                            const isSelected = selectedItems.some(item => item.id === projectId);
                                            const selectedSpec = selectedItems.find(item => item.id === projectId);
                                            
                                            return (
                                                <div 
                                                    key={projectId}
                                                    className={`${styles.projectCard} ${isSelected ? styles.selected : ''}`}
                                                    data-id={projectId}
                                                    onClick={() => openSpecModal(projectId)}
                                                >
                                                    <div 
                                                        className={styles.projectImage}
                                                        style={{ backgroundImage: `url('https://picsum.photos/id/${237 + Object.keys(projectMap).indexOf(projectId)}/300/200')` }}
                                                    ></div>
                                                    <i className={`fa fa-check-circle ${styles.selectedIndicator} ${isSelected ? '' : styles.hidden}`}></i>
                                                    <div className={styles.projectName}>{project.name}</div>
                                                    <div className={styles.projectSpecs}>
                                                        可选时长: {project.specs.map(s => s.duration).join('/')}
                                                    </div>
                                                    <div className={styles.selectedPrice}>
                                                        {isSelected ? `${selectedSpec.duration} ¥${selectedSpec.price.toFixed(2)}` : '请选择规格'}
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>

                                    {filteredServices().length === 0 && (
                                        <div className={styles.noResults}>
                                            <i className="fa fa-search-minus text-3xl mb-2"></i>
                                            <p>没有找到匹配的服务项目</p>
                                        </div>
                                    )}
                                </div>
                            )}

                            {/* 订单记录内容 */}
                            {activeTab === 'orders' && (
                                <div className={styles.tabContentActive}>
                                    <div className={styles.orderList}>
                                        {filteredOrders().map(order => (
                                            <div 
                                                key={order.id}
                                                className={`${styles.orderItem} ${selectedOrderId === order.id ? styles.active : ''}`}
                                                onClick={() => loadOrderDetails(order.id)}
                                            >
                                                <div className={styles.orderHeader}>
                                                    <div className={styles.orderClient}>{order.clientName} ({order.clientPhone})</div>
                                                    <div className={styles.orderTime}>{order.createTime}</div>
                                                </div>
                                                <div className={styles.orderProjects}>
                                                    {order.items.map(item => `${item.name}(${item.duration})`).join('、')}
                                                </div>
                                                <div className={styles.flexEnd}>
                                                    <div className={styles.orderTotal}>¥{order.totalAmount.toFixed(2)}</div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>

                                    {filteredOrders().length === 0 && (
                                        <div className={styles.noResults}>
                                            <i className="fa fa-file-text-o text-3xl mb-2"></i>
                                            <p>没有找到匹配的订单记录</p>
                                        </div>
                                    )}
                                </div>
                            )}

                            {/* 预约安排内容 */}
                            {activeTab === 'appointments' && (
                                <div className={styles.tabContentActive}>
                                    <div className={styles.orderList}>
                                        {filteredAppointments().map(appointment => (
                                            <div 
                                                key={appointment.id}
                                                className={`${styles.orderItem} ${selectedAppointmentId === appointment.id ? styles.active : ''}`}
                                                onClick={() => loadAppointmentDetails(appointment.id)}
                                            >
                                                <div className={styles.orderHeader}>
                                                    <div className={styles.orderClient}>{appointment.clientName} ({appointment.clientPhone})</div>
                                                    <div className={styles.orderTime}>{appointment.appointmentTime}</div>
                                                </div>
                                                <div className={styles.orderProjects}>
                                                    {appointment.items.map(item => `${item.name}(${item.duration})`).join('、')}
                                                </div>
                                                <div className={styles.flexBetween}>
                                                    <div>
                                                        {appointment.staffName && (
                                                            <span className={styles.tag}>{appointment.staffName}</span>
                                                        )}
                                                        {appointment.roomName && (
                                                            <span className={styles.tag}>{appointment.roomName.split(' - ')[0]}</span>
                                                        )}
                                                    </div>
                                                    <div className={styles.orderTotal}>¥{appointment.totalAmount.toFixed(2)}</div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>

                                    {filteredAppointments().length === 0 && (
                                        <div className={styles.noResults}>
                                            <i className="fa fa-calendar-o text-3xl mb-2"></i>
                                            <p>没有找到匹配的预约记录</p>
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>
                    </div>

                    {/* 右侧：客户信息、已选项目、支付方式和总金额 */}
                    <div className={styles.rightColumn}>
                        <div className={styles.cardStyle}>
                            <h2 className={styles.orderTitle}>
                                <i className="fa fa-file-text-o mr-2"></i> 订单信息
                            </h2>

                            <div className={styles.spaceContainer}>
                                {/* 客户信息部分 */}
                                <div>
                                    <h3 className={styles.sectionTitle}>客户信息</h3>
                                    <div>
                                        <label className={styles.label}>电话号码 <span className={styles.required}>*</span></label>
                                        <input 
                                            type="tel" 
                                            className={styles.inputField} 
                                            placeholder="请输入客户电话号码" 
                                            value={clientPhone}
                                            onChange={(e) => setClientPhone(e.target.value)}
                                            required
                                        />
                                    </div>
                                </div>

                                {/* 已选项目 */}
                                <div>
                                    <h3 className={styles.sectionTitle}>已选项目</h3>
                                    <div className={styles.selectedItemsContainer}>
                                        {selectedItems.length === 0 ? (
                                            <div className={styles.emptySelectedItems}>
                                                请从左侧选择服务项目
                                            </div>
                                        ) : (
                                            selectedItems.map(item => (
                                                <div key={item.specId} className={styles.selectedItem}>
                                                    <div className={styles.selectedItemInfo}>
                                                        <div className={styles.selectedItemName}>{item.name}</div>
                                                        <div className={styles.selectedItemSpec}>{item.duration}</div>
                                                    </div>
                                                    <div className={styles.selectedItemPrice}>¥{item.price.toFixed(2)}</div>
                                                    <div 
                                                        className={styles.removeItem}
                                                        onClick={() => removeSelectedItem(item.specId)}
                                                    >
                                                        <i className="fa fa-times-circle"></i>
                                                    </div>
                                                </div>
                                            ))
                                        )}
                                    </div>
                                </div>

                                {/* 员工选择 - 订单选中时隐藏 */}
                                {!selectedOrderId && (
                                    <div>
                                        <h3 className={styles.sectionTitle}>理疗师</h3>
                                        <select 
                                            className={styles.selectField}
                                            value={selectedStaff}
                                            onChange={(e) => setSelectedStaff(e.target.value)}
                                        >
                                            <option value="">请选择理疗师</option>
                                            <option value="1">李医师</option>
                                            <option value="2">王医师</option>
                                            <option value="3">张医师</option>
                                            <option value="4">刘医师</option>
                                            <option value="5">陈医师</option>
                                        </select>
                                    </div>
                                )}

                                {/* 房间选择 - 订单选中时隐藏 */}
                                {!selectedOrderId && (
                                    <div>
                                        <h3 className={styles.sectionTitle}>理疗房间</h3>
                                        <select 
                                            className={styles.selectField}
                                            value={selectedRoom}
                                            onChange={(e) => setSelectedRoom(e.target.value)}
                                        >
                                            <option value="">请选择房间</option>
                                            <option value="1">1号房 - 艾灸房</option>
                                            <option value="2">2号房 - 推拿房</option>
                                            <option value="3">3号房 - 理疗房</option>
                                            <option value="4">4号房 - VIP单间</option>
                                            <option value="5">5号房 - 双人房</option>
                                        </select>
                                    </div>
                                )}

                                {/* 支付方式 */}
                                {selectedOrderId && (
                                    <div>
                                        <h3 className={styles.sectionTitle}>支付方式</h3>
                                        <div className={styles.paymentMethodsGrid}>
                                            <div 
                                                className={`${styles.paymentMethod} ${selectedPaymentMethod === 'cash' ? styles.selected : ''}`}
                                                onClick={() => setSelectedPaymentMethod('cash')}
                                            >
                                                <i className={`fa fa-check-circle ${styles.paymentCheckmark} ${selectedPaymentMethod === 'cash' ? '' : styles.hidden}`}></i>
                                                <div className={styles.paymentIcon}>
                                                    <i className="fa fa-money"></i>
                                                </div>
                                                <div className={styles.paymentInfo}>
                                                    <div className={styles.paymentName}>现金支付</div>
                                                    <div className={styles.paymentDesc}>使用现金完成支付</div>
                                                </div>
                                            </div>

                                            <div 
                                                className={`${styles.paymentMethod} ${selectedPaymentMethod === 'wechat' ? styles.selected : ''}`}
                                                onClick={() => setSelectedPaymentMethod('wechat')}
                                            >
                                                <i className={`fa fa-check-circle ${styles.paymentCheckmark} ${selectedPaymentMethod === 'wechat' ? '' : styles.hidden}`}></i>
                                                <div className={styles.paymentIcon}>
                                                    <i className="fa fa-weixin"></i>
                                                </div>
                                                <div className={styles.paymentInfo}>
                                                    <div className={styles.paymentName}>微信支付</div>
                                                    <div className={styles.paymentDesc}>使用微信扫码支付</div>
                                                </div>
                                            </div>

                                            <div 
                                                className={`${styles.paymentMethod} ${selectedPaymentMethod === 'alipay' ? styles.selected : ''}`}
                                                onClick={() => setSelectedPaymentMethod('alipay')}
                                            >
                                                <i className={`fa fa-check-circle ${styles.paymentCheckmark} ${selectedPaymentMethod === 'alipay' ? '' : styles.hidden}`}></i>
                                                <div className={styles.paymentIcon}>
                                                    <i className="fa fa-credit-card"></i>
                                                </div>
                                                <div className={styles.paymentInfo}>
                                                    <div className={styles.paymentName}>支付宝</div>
                                                    <div className={styles.paymentDesc}>使用支付宝扫码支付</div>
                                                </div>
                                            </div>

                                            <div 
                                                className={`${styles.paymentMethod} ${selectedPaymentMethod === 'card' ? styles.selected : ''}`}
                                                onClick={() => setSelectedPaymentMethod('card')}
                                            >
                                                <i className={`fa fa-check-circle ${styles.paymentCheckmark} ${selectedPaymentMethod === 'card' ? '' : styles.hidden}`}></i>
                                                <div className={styles.paymentIcon}>
                                                    <i className="fa fa-cc-visa"></i>
                                                </div>
                                                <div className={styles.paymentInfo}>
                                                    <div className={styles.paymentName}>银行卡支付</div>
                                                    <div className={styles.paymentDesc}>使用银行卡刷卡支付</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* 金额汇总 */}
                                <div>
                                    <div className={styles.amountSummary}>
                                        <div className={styles.amountRow}>
                                            <span>小计</span>
                                            <span>¥{subtotal.toFixed(2)}</span>
                                        </div>
                                        <div className={styles.amountRow}>
                                            <span>优惠</span>
                                            <span>¥{discount.toFixed(2)}</span>
                                        </div>
                                        <div className={`${styles.amountRow} ${styles.total}`}>
                                            <span>总计</span>
                                            <span>¥{total.toFixed(2)}</span>
                                        </div>
                                    </div>
                                </div>

                                {/* 备注信息 */}
                                <div>
                                    <h3 className={styles.sectionTitle}>备注</h3>
                                    <textarea 
                                        className={styles.inputField} 
                                        rows="3" 
                                        placeholder="请输入备注信息（可选）" 
                                        value={notes}
                                        onChange={(e) => setNotes(e.target.value)}
                                    ></textarea>
                                </div>
                            </div>
                        </div>

                        {/* 操作按钮 */}
                        <div className={styles.actionButtonsContainer}>
                            <div className={styles.actionButtons}>
                                <button 
                                    className={styles.btnSecondary} 
                                    onClick={selectedOrderId || selectedAppointmentId ? resetSelection : resetForm}
                                >
                                    <i className="fa fa-refresh mr-1.5"></i> 
                                    {selectedOrderId || selectedAppointmentId ? '取消选择' : '重置'}
                                </button>
                                
                                {selectedOrderId && (
                                    <button 
                                        className={styles.btnTertiary} 
                                        onClick={confirmOrderChanges}
                                    >
                                        <i className="fa fa-save mr-1.5"></i> 确认修改
                                    </button>
                                )}
                                
                                <button 
                                    className={styles.btnPrimary} 
                                    onClick={handleActionButtonClick}
                                >
                                    {selectedOrderId ? (
                                        <><i className="fa fa-credit-card mr-1.5"></i> 支付</>
                                    ) : selectedAppointmentId ? (
                                        <><i className="fa fa-check mr-1.5"></i> 确认安排</>
                                    ) : (
                                        <><i className="fa fa-plus mr-1.5"></i> 生成</>
                                    )}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </main>

            {/* 规格选择弹窗 */}
            {specModalOpen && currentProjectId && (
                <div className={styles.modalBackdrop} onClick={closeSpecModal}>
                    <div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
                        <h3 className={styles.modalTitle}>选择{projectMap[currentProjectId].name}规格</h3>
                        <div className={styles.specOptions}>
                            {projectMap[currentProjectId].specs.map(spec => (
                                <div 
                                    key={spec.id}
                                    className={styles.specOption}
                                    onClick={() => selectSpec(spec)}
                                >
                                    <div className={styles.specName}>{spec.duration}</div>
                                    <div className={styles.specPrice}>¥{spec.price.toFixed(2)}</div>
                                </div>
                            ))}
                        </div>
                        <button className={styles.btnSecondary} onClick={closeSpecModal}>关闭</button>
                    </div>
                </div>
            )}
        </div>
    );
};

export default Cure;
